<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChTalkKeywordCateMapper;
use App\CustHub\Mapper\ChTalkKeywordMapper;
use App\CustHub\Model\ChWordGroup;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use function Hyperf\Collection\data_get;

class ChTalkKeywordCateService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChTalkKeywordMapper $keywordMapper;

    public function __construct(ChTalkKeywordCateMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function getPageList(?array $params = null, bool $isScope = true): array
    {
        $type = data_get($params,'type',0);
        $mainUid = $params['main_uid'];
        $uid = $params['uid'];
        $pageSize = (int)data_get($params,'page_size',10);
        $p = ChWordGroup::query()
            ->select(['id','title as name'])
            ->where('main_uid',$mainUid)
            ->when($type == 1,function ($query) use ($uid){
                $query->where('cs_id',$uid);
            })
            ->where('is_personal',$type)
            ->where('p_id',0)
            ->orderBy('sort','desc')
            ->paginate($pageSize);

        $items = $p->items();

        $ids = array_column($items,'id');

        $childMap = ChWordGroup::query()
            ->select(['id','title as name','p_id'])
            ->where('main_uid',$mainUid)
            ->whereIn('p_id',$ids)
            ->get()
            ->groupBy('p_id');

        $p->getCollection()->transform(function ($item) use ($childMap){
            $item['child'] = $childMap[$item['id']] ?? [];
            return $item;
        });
        $data = $this->mapper->setPaginate($p);
        $default = [
            [
                'id' => 0,
                'name' => '默认分组',
                'child' =>  []
            ]
        ];
        $data['items'] = array_merge($default,$data['items']);
        return $data;
    }


    /**
     * 删除分类
     * @param mixed $id
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function deleteCate(mixed $id): bool
    {
        if($this->keywordMapper->checkExistsByCateId($id)){
            throw new NormalStatusException("当前分类下存在快捷语，不可删除~");
        }

        return $this->mapper->delete([$id]);
    }
}